﻿using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Threading;
using Lm.Core.TaskQueue;
using log4net;
using Microsoft.VisualBasic;
using Modules.ActionRun;
using Modules.Monitoring;
using Modules.MSentEvent;
using Modules.Units;
using Newtonsoft.Json;
using Prism.Events;
using Prism.Ioc;
using Prism.Regions;
using RabbitMQ;
using RabbitMQ.Client;
using Sorting.App.Controls;
using Sorting.App.Models;
using Sorting.App.Models.Enum;
using Sorting.App.Models.Model;
using Sorting.App.Services;
using static Sorting.App.Controls.MyMessageBox;

namespace Sorting.App.Views;

/// <summary>
///     StartLoading.xaml 的交互逻辑
/// </summary>
public partial class StartLoading : UserControl
{
    private readonly IContainerExtension _container;

    private readonly IEventAggregator _ea;
    private readonly IRegionManager _regionManager;
    private readonly TaskQueueHelper _taskQueueHelper;
    private readonly MonitoringHeler monitoringHeler;

    private readonly LoginService _loginService;
    private ILog log = LogManager.GetLogger(typeof(StartLoading));
    /// <summary>
    ///     需要检查的项目
    /// </summary>
    private readonly int CheckProject = 10;


    private bool IsStartSucess;


    /// <summary>
    ///     百分比
    /// </summary>
    private int PerNum = 10;

    public StartLoading()
    {
        InitializeComponent();
    }

    public StartLoading(IContainerExtension container, IRegionManager manager,
                        IEventAggregator eventAggregator,
                        LoginService loginService)
    {
        InitializeComponent();
        _container = container;
        _regionManager = manager;
        _ea = eventAggregator;
        _loginService = loginService;



    }


    private void LoadingFinish(bool obj)
    {

    }

    private void StartLoading_OnLoaded(object sender, RoutedEventArgs e)
    {

        Task.Run(() =>
                  {
                      UpdateProgressBarDelegate updateProgressBaDelegate = progressBar.SetValue;
                      for (var i = 0; i <= CheckProject; i++)
                      {
                          switch (i)
                          {
                              case 0:
                                  Dispatcher.Invoke(async() =>
                                  {
                                      //启动设备动作执行服务
                                    
                                      try
                                      {
                                          //打开后台服务进程
                                          Process p = new Process();

                                          DirectoryInfo di = new DirectoryInfo(string.Format(@"{0}", System.Environment.CurrentDirectory));
                                          string servicePath = Path.Combine(di.FullName, "WorkerServices", "SortingWorkerService.exe");

                                          p.StartInfo = new ProcessStartInfo(servicePath);


                                          if (p.Start())
                                          {
                                              log.Info("后台服务启动成功" + DateTime.Now.ToString());
                                            

                                          }

                                      }
                                      catch (Exception ex)
                                      {

                                          MessageBox.Show(ex.ToString());

                                          throw;
                                      }

                                      //初始化传感器信号
                                      AppsettingUnits.SignalModel = new SensorSignalModel();
                                      //初始化RabbitMq队列    清除所有已有消息

                                      MQHelperFactory.ClientOptionBuilder();

                                      var mqFacSorting = MQHelperFactory.Sorting;


                                      mqFacSorting().ClearAllMsg("Sorting.InBagPoint");
                                      mqFacSorting().ClearAllMsg("Sorting.EndBagPoint");
                                      mqFacSorting().ClearAllMsg("Sorting.SendToLoc");
                                      mqFacSorting().ClearAllMsg("Sorting.SendFinish");

                                      var mqFacSortingView = MQHelperFactory.SortingView;

                                      mqFacSortingView().ClearAllMsg("SortingView.EquInitial");
                                      mqFacSortingView().ClearAllMsg("SortingView.Error");
                                      mqFacSortingView().ClearAllMsg("SortingView.SendFinish");
                                      mqFacSortingView().ClearAllMsg("SortingView.PutCount");
                                      mqFacSortingView().ClearAllMsg("SortingView.CountFinish");
                                      mqFacSortingView().ClearAllMsg("SortingView.SendStartKeyout");
                                     




                                      //查看设备后台执行服务有没有开启，没开启尝试调用服务开启





                                  });
                                  Thread.Sleep(500);
                                  break;


                              case 1:
                                  //设备初始化
                                  try
                                  {
                                      //log.Info("设备初始化" + DateTime.Now.ToString());

                                      //MQHelperFactory.SortingView().SendMsg<RabbitSend<bool>>("SortingView.EquInitial", new RabbitSend<dynamic>
                                      //{
                                      //    TaskData = true,
                                      //    TaskMessage = "任务初始",
                                      //    TaskType = "任务初始"
                                      //});

                                      Thread.Sleep(500);
                                  }
                                  catch (Exception ex)
                                  {

                                      log.Info(ex);
                                  }
                                 
                                  break;
                              case 2:
                                  var status = AppsettingUnits.SignalModel.BackOrgState;
                                  if (status != 2)
                                  {
                                      Thread.Sleep(500);
                                  }

                                  break;
                              case 3:

                                  Thread.Sleep(500);
                                  break;
                              case 5:

                                  Thread.Sleep(500);
                                  break;
                              case 7:
                                  status = AppsettingUnits.SignalModel.BackOrgState;
                                  if (status == 2)
                                  {
                                      log.Info("初始化完成" + DateTime.Now.ToString());

                                  }

                                  break;

                          }

                          Dispatcher.Invoke(() =>
                          {
                              PerNum += (int)progressBar.Maximum / CheckProject;
                          });
                          Thread.Sleep(10);
                          Dispatcher.Invoke(updateProgressBaDelegate,
                                             DispatcherPriority.Background, RangeBase.ValueProperty,
                                             Convert.ToDouble(PerNum));
                          if (PerNum == 100) IsStartSucess = true;
                      }

                      Dispatcher.Invoke(() =>

                      {
                          if (IsStartSucess)
                          {
                              Thread.Sleep(1000);
                              _ea.GetEvent<LoadingSentEvent>().Publish(0);
                          }
                      });
                  });
    }


    private delegate void UpdateProgressBarDelegate(DependencyProperty dp, object value);

    private void UserControl_Unloaded(object sender, RoutedEventArgs e)
    {
        log.Info("设备初始化" + DateTime.Now.ToString());

        MQHelperFactory.SortingView().SendMsg<RabbitSend<bool>>("SortingView.EquInitial", new RabbitSend<dynamic>
        {
            TaskData = true,
            TaskMessage = "任务初始",
            TaskType = "任务初始"
        });
    }
}